<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
	#div1 {width: 100px; height: 100px; background: red; position: absolute;}
	#div2 {width: 700px; height: 500px; background: #CCC; position: relative;}
</style>
<script>
window.onload = function()
{
		var oDiv = document.getElementById('div1');
		var oDiv2 = document.getElementById('div2');
	
		var disX =0 ;
		var disY = 0;
	
		oDiv.onmousedown= function(ev)
		{
				//clientX clientY 鼠标坐标
				var oEvent = ev||event;
				disX = oEvent.clientX- oDiv.offsetLeft ;
				disY = oEvent.clientY -oDiv.offsetTop ;

				document.onmousemove= function(ev)
				{
						var oEvent = ev||event;
						var left = oEvent.clientX - disX;
						var top = oEvent.clientY - disY;
						var rang = 50;
						
						if(left<rang)
						{
								left = 0;
						}
						if(left > oDiv2.offsetWidth -oDiv.offsetWidth-rang)
						{
								left = oDiv2.offsetWidth -oDiv.offsetWidth;
						}
						if(top<rang)
						{
								top = 0;
						}
						if(top > oDiv2.offsetHeight -oDiv.offsetHeight-rang)
						{
								top = oDiv2.offsetHeight -oDiv.offsetHeight;
						}
					
						oDiv.style.left = left + 'px';
						oDiv.style.top = top + 'px';
						
				};
				
			document.onmouseup = function()
			{
					document.onmousemove =null;
					document.onmouseup=null;
			};
			
		};
};
</script>
</head>

<body>
<div id="div2">
	<div id="div1"></div>
</div>
</body>
</html>
